package com.tnsw.noxnox.lab;

import java.util.ArrayList;
import java.util.Set;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

import com.tnsw.coreutils.AsyncManager;
import com.tnsw.coreutils.http.THttpBase;
import com.tnsw.coreutils.http.THttpListener;
import com.tnsw.coreutils.http.THttpPost;
import com.tnsw.noxnox.FragmentWithAdapter;
import com.tnsw.noxnox.R;
import com.tnsw.noxnox.YoutubeFragment;
import com.tnsw.noxnox.db.DBManager;
import com.tnsw.noxnox.dialog.FragmentDialogBuilder;
import com.tnsw.noxnox.dialog.FragmentDialogInterface;
import com.tnsw.noxnox.settopbox.PortScanner;
import com.tnsw.noxnox.settopbox.PortScannerListener;
import com.tnsw.noxnox.streamer.StreamerService;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class LabWebViewFragment extends FragmentWithAdapter implements THttpListener, android.content.DialogInterface.OnClickListener, OnClickListener, PortScannerListener, FragmentDialogInterface {
	
	private String tag = "LabWebViewFragment";
	private DBManager dbm;
	private AsyncManager asyncManager;
	private ViewGroup root;
	private Button btnStartPortScan, btnCountThread;
	
	private ArrayList<String> ipAddressList;
	private FragmentDialogBuilder fd;
	private int dialogId;
	
	public LabWebViewFragment() {
		super();
	}
	
	public LabWebViewFragment(Context context, FragmentPagerAdapter pagerAdapter) {
		super(context, pagerAdapter);
		Log.d(tag, "Constructor(context)");
		
		this.context = context;
		this.dbm = DBManager.getInstance(this.context);
		this.asyncManager = AsyncManager.getInstance();
		
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		this.root = (ViewGroup) inflater.inflate(com.tnsw.noxnox.R.layout.lab_webview, null);
		
		this.btnStartPortScan = (Button) this.root.findViewById(R.id.btnStartPortScan);
		this.btnStartPortScan.setOnClickListener(this);
		
		this.btnCountThread = (Button) this.root.findViewById(R.id.btnCountThread);
		this.btnCountThread.setOnClickListener(this);
		
		return(root);
	}
	
	public static Fragment newInstance(Context context, FragmentPagerAdapter pagerAdapter) {
		Log.d("LabWebViewFragment", "newInstance()");
		LabWebViewFragment f = new LabWebViewFragment(context, pagerAdapter);
		return(f);
	}

	@Override
	public void onClick(View v) {
		if (v == this.btnStartPortScan) {
			Log.d(tag, "Start ScanPort");
			
			PortScanner scanner = new PortScanner(this.context);
			scanner.setListener(this);
			try {
				scanner.scan();	
			} catch (Exception e) {
				
			}
						
			this.fd = new FragmentDialogBuilder(this.context, this);			
			fd.setStyle(DialogFragment.STYLE_NORMAL, fd.getTheme());
			fd.setCancelable(false);
			fd.show(this.getFragmentManager(), "0");
			
			
		} else if (v == this.btnCountThread) {
			int activeCount = Thread.activeCount();
			Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
			
			Log.d(tag, "ThreadCount(activeCount=" + activeCount + ", size=" + threadSet.size() + ")");			
		}
	}

	@Override
	public void onComplete(PortScanner sender, ArrayList<String> ipAddressList) {
		Log.d(tag, "onCompleted:");
		for (String ipAddress : ipAddressList) {
			Log.d(tag, "OK:" + ipAddress);
		}
		
		this.ipAddressList = ipAddressList;
		
		Log.d(tag, "class=" + this.getFragmentManager().findFragmentByTag("0").getClass().getName());
		FragmentDialogBuilder fd = (FragmentDialogBuilder) this.getFragmentManager().findFragmentByTag("0");
		fd.dismiss();
		
		this.dialogId = 1;
		fd.setCancelable(true);
		fd.show(this.getFragmentManager(), "0");
	}

	@Override
	public void onSingleCompleted(PortScanner sender, String ipAddress, boolean isOK, String detail) {
		Log.d(tag, "onSingleCompleted:" + ipAddress + ", isOK=" + isOK + ", detail=" + detail);
		
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		AlertDialog.Builder dialog = null;
		dialog = new AlertDialog.Builder(this.context);
		
		if (this.dialogId == 0) {
			
			dialog.setTitle("Please wait..");
			dialog.setPositiveButton("OK", null);
			dialog.setCancelable(false);
			
		} else if (this.dialogId == 1){
			dialog.setTitle("Choose TV");
			if (this.ipAddressList != null) {
				String[] ips = new String[this.ipAddressList.size()];
				int i;
				for (i = 0; i < ips.length; i++) {
					ips[i] = this.ipAddressList.get(i);
				}
				dialog.setItems(ips, this);
			}
			
		}
		
		return(dialog.create());
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		Log.d(tag, "onClick:dialog=" + dialog.getClass().getName() + ", which=" + which);
		String selectedIP = this.ipAddressList.get(which);
		
		StreamerService ss = StreamerService.getInstance();
		if (ss != null) {
			int primarykey = 123;
			String requestUrl = "http://" + selectedIP + ":7778/stb/play?id=" + String.valueOf(primarykey);
			THttpPost p = new THttpPost(this.context, requestUrl);
			p.setListener(this);
			p.setSessionName("play");
			
			ArrayList<NameValuePair> a = new ArrayList<NameValuePair>();
			String mediaUrl = ss.getMediaPlayUrl(primarykey);
			a.add(new BasicNameValuePair("url", mediaUrl));
			
			try {
				p.setEntity(new UrlEncodedFormEntity(a));
				p.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "0");
			} catch (Exception e) {
				Log.e(tag, "Error on trying to send command to TV - " + e.toString(), e);
			}
			
		}
		
	}

	@Override
	public void onProgressUpdate(THttpBase sender, Integer[] values) {
		
	}

	@Override
	public void onPostExecute(THttpBase sender, Long result) {
		
	}

	@Override
	public void onNewLineFetchBG(THttpBase sender, String line) {
		
	}

	@Override
	public void onReceiveResponseBG(THttpBase sender) {
		
	}

	@Override
	public void onBinaryReadBG(THttpBase sender, byte[] b) {
		
	}
}
